package cn.luyou.admin.service.impl;

import cn.hutool.json.JSONUtil;
import cn.luyou.admin.dto.RuleConfigDTO;
import cn.luyou.admin.entity.ExamRule;
import cn.luyou.admin.mapper.ExamRuleMapper;
import cn.luyou.admin.service.ExamRuleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class ExamRuleServiceImpl extends ServiceImpl<ExamRuleMapper, ExamRule> implements ExamRuleService {

    @Override
    public IPage<ExamRule> getRules(Integer pageNum, Integer pageSize, String keyword) {
        LambdaQueryWrapper<ExamRule> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            wrapper.like(ExamRule::getRuleName, keyword)
                    .or()
                    .like(ExamRule::getSubject, keyword);
        }
        wrapper.orderByDesc(ExamRule::getCreatedTime);
        return this.page(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    @Transactional
    public ExamRule addRule(ExamRule rule) {
        // 验证规则配置
        validateRuleConfig(rule.getRuleConfig());
        
        // 检查规则名是否存在
        if (this.count(new LambdaQueryWrapper<ExamRule>()
                .eq(ExamRule::getRuleName, rule.getRuleName())) > 0) {
            throw new IllegalArgumentException("规则名称已存在");
        }
        
        this.save(rule);
        return rule;
    }

    @Override
    @Transactional
    public void updateRule(ExamRule rule) {
        // 验证规则配置
        validateRuleConfig(rule.getRuleConfig());
        
        ExamRule existingRule = this.getById(rule.getId());
        if (existingRule == null) {
            throw new IllegalArgumentException("规则不存在");
        }
        
        // 检查规则名是否与其他规则冲突
        if (!existingRule.getRuleName().equals(rule.getRuleName())) {
            if (this.count(new LambdaQueryWrapper<ExamRule>()
                    .eq(ExamRule::getRuleName, rule.getRuleName())) > 0) {
                throw new IllegalArgumentException("规则名称已存在");
            }
        }
        
        this.updateById(rule);
    }

    @Override
    @Transactional
    public void deleteRule(Long id) {
        ExamRule rule = this.getById(id);
        if (rule == null) {
            throw new IllegalArgumentException("规则不存在");
        }
        
        this.removeById(id);
    }

    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        ExamRule rule = this.getById(id);
        if (rule == null) {
            throw new IllegalArgumentException("规则不存在");
        }
        
        rule.setStatus(status);
        this.updateById(rule);
    }

    @Override
    public void validateRuleConfig(String ruleConfig) {
        try {
            // 解析JSON配置
            RuleConfigDTO config = JSONUtil.toBean(ruleConfig, RuleConfigDTO.class);

            // 基本验证
            if (config.getQuestionTypes() == null || config.getQuestionTypes().isEmpty()) {
                throw new IllegalArgumentException("规则配置必须包含至少一种题型");
            }

            // 验证每种题型的配置
            for (RuleConfigDTO.QuestionTypeConfig typeConfig : config.getQuestionTypes()) {
                if (!StringUtils.hasText(typeConfig.getType())) {
                    throw new IllegalArgumentException("题型不能为空");
                }
                if (!StringUtils.hasText(typeConfig.getDifficulty())) {
                    throw new IllegalArgumentException("难度不能为空");
                }
                if (typeConfig.getCount() == null || typeConfig.getCount() <= 0) {
                    throw new IllegalArgumentException("题目数量必须大于0");
                }
                if (typeConfig.getScorePerQuestion() == null || typeConfig.getScorePerQuestion() <= 0) {
                    throw new IllegalArgumentException("每题分值必须大于0");
                }
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("规则配置格式错误：" + e.getMessage());
        }
    }

    @Override
    public ExamRule getRuleById(Long id) {
        return this.getById(id);
    }
} 
